import sys
from PyQt6.QtWidgets import QApplication
from PyQt6 import QtWidgets,QtCore,QtGui
import cv2
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
import PyQt6
from faceRecognition import Ui_face_recognition
from face_rec import FaceRec
from more_faces_detect import MoreFaceDetect


class QmyRec(QWidget):
    # 跳转信号
    switch_window5 = QtCore.pyqtSignal()

    def __init__(self,parent=None):
        super().__init__(parent)
        self.face_reco = Ui_face_recognition()
        self.face_reco.setupUi(self)
        self.setGeometry(700, 800, 700, 800)
        self.center()
        self.setWindowTitle('比奇堡在逃海绵')
        self.timer_camera = QtCore.QTimer()
        self.cap = cv2.VideoCapture()
        self.CAM_NUM = 0
        self.slot_rec()
        # text = open('../users/all_people.txt').read()
        # self.face_reco.allpeople.setMarkdown(text)
        self.face_reco.return_2.clicked.connect(self.goRec_Main)

    def goRec_Main(self):
        self.switch_window5.emit()

    def paintEvent(self, event):
        painter = QPainter(self)
        pixmap = QPixmap("人脸录入.png")
        # 绘制窗口背景，平铺到整个窗口，随着窗口改变而改变
        painter.drawPixmap(self.rect(), pixmap)
        text = open('users/all_people.txt').read()
        self.face_reco.allpeople.setMarkdown(text)


    def slot_rec(self):
        self.face_reco.openPhoto.clicked.connect(self.button_open_camera_click)
        self.timer_camera.timeout.connect(self.show_photo)
        self.face_reco.closePhoto.clicked.connect(self.closeCamera)

    '''打开摄像头'''

    def button_open_camera_click(self):
        if self.timer_camera.isActive() == False:
            flag = self.cap.open(self.CAM_NUM)
            if flag == False:
                msg = QtWidgets.QMessageBox.warning(
                    PyQt6.QtWidgets.QApplication.activeWindow(), u"Warning", u"请检测相机与电脑是否连接正确",
                    buttons=QtWidgets.QMessageBox.StandardButton.Ok,
                    defaultButton=QtWidgets.QMessageBox.StandardButton.NoButton)
            else:
                self.timer_camera.start(20)
        else:
            self.timer_camera.stop()  # 关闭定时器
            self.cap.release()  # 释放视频流
            self.face_reco.facePhotos.clear()  # 清空视频显示区域

    '''显示识别视频画面'''
    def show_photo(self):
        QApplication.processEvents()
        flag, self.photo = self.cap.read()
        # 单人人脸识别
        # self.face_rec = FaceRec()
        # self.face_rec.recognition(self.photo)
        # 多人识别
        self.more_face = MoreFaceDetect()
        self.more_face.detect(self.photo)
        self.face_reco.similar.setText(str(self.more_face.similarity))
        self.face_reco.finalName.setText(self.more_face.name)
        # self.photo = cv2.flip(self.photo, 1)  # 左右翻转
        show = cv2.cvtColor(self.photo, cv2.COLOR_BGR2RGB)
        # 视频流的长和宽
        height, width = self.photo.shape[:2]
        showPhoto = QtGui.QImage(show.data, width, height, QtGui.QImage.Format.Format_RGB888)
        ratio = max(width / self.face_reco.facePhotos.width(), height / self.face_reco.facePhotos.height())
        showPhoto.setDevicePixelRatio(ratio)
        # 视频流置于label中间部分播放
        self.face_reco.facePhotos.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.face_reco.facePhotos.setPixmap(QtGui.QPixmap.fromImage(showPhoto))
        self.face_reco.facePhotos.setScaledContents(True)

    '''关闭录入摄像头'''

    def closeCamera(self):

        # self.face_reco.openPhoto.setEnabled(True)
        # self.face_reco.closePhoto.setEnabled(False)
        self.timer_camera.stop()
        self.cap.release()
        self.face_reco.facePhotos.clear()

    '''屏幕居中'''
    def center(self):
        qr = self.frameGeometry()  # 得到一个指定主窗口几何形状的矩形
        cp = self.screen().availableGeometry().center()  # 计算出显示器的分辨率，通过分辨率得出中心点
        qr.moveCenter(cp)  # 设置为屏幕的中心，矩形大小不变
        self.move(qr.topLeft())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('logo.ico'))
    myWidget = QmyRec()
    myWidget.show()
    sys.exit(app.exec())



# import sys
# from PyQt6.QtWidgets import QApplication
# from PyQt6 import QtWidgets,QtCore,QtGui
# import cv2
# from PyQt6.QtGui import *
# from PyQt6.QtWidgets import *
# import PyQt6
# from faceRecognition import Ui_face_recognition
# from face_rec import FaceRec
# from more_faces_detect import MoreFaceDetect
# import numpy as np


# class CameraThread(QtCore.QThread):
#     change_pixmap_signal = QtCore.pyqtSignal(np.ndarray)

#     def __init__(self, cam_num=0, fps=10):
#         super().__init__()
#         self.cap = cv2.VideoCapture(cam_num)
#         self.running = True
#         self.fps = fps

#     def run(self):
#         while self.running:
#             flag, frame = self.cap.read()
#             if flag:
#                 self.change_pixmap_signal.emit(frame)
#             # 控制帧率，避免每秒处理过多帧
#             self.msleep(int(1000 / self.fps))

#     def stop(self):
#         self.running = False
#         self.cap.release()



# class QmyRec(QWidget):
#     # 跳转信号
#     switch_window5 = QtCore.pyqtSignal()

#     def __init__(self, parent=None):
#         super().__init__(parent)
#         self.face_reco = Ui_face_recognition()
#         self.face_reco.setupUi(self)
#         self.setGeometry(700, 800, 700, 800)
#         self.center()
#         self.setWindowTitle('比奇堡在逃海绵')

#         self.camera_thread = None  # 摄像头线程
#         self.more_face = MoreFaceDetect()  # 多人脸识别

#         self.face_reco.return_2.clicked.connect(self.goRec_Main)
#         self.face_reco.openPhoto.clicked.connect(self.start_camera)
#         self.face_reco.closePhoto.clicked.connect(self.stop_camera)
#         self.frame_count =0

#     def goRec_Main(self):
#         self.switch_window5.emit()

#     def paintEvent(self, event):
#         painter = QPainter(self)
#         pixmap = QPixmap("人脸录入.png")
#         painter.drawPixmap(self.rect(), pixmap)
#         text = open('users/all_people.txt').read()
#         self.face_reco.allpeople.setMarkdown(text)

#     def start_camera(self):
#         if not self.camera_thread:
#             # 创建并启动摄像头线程
#             self.camera_thread = CameraThread()
#             self.camera_thread.change_pixmap_signal.connect(self.update_image)
#             self.camera_thread.start()
#         else:
#             self.stop_camera()  # 如果摄像头已经在运行，停止它

#     def stop_camera(self):
#         if self.camera_thread:
#             self.camera_thread.stop()
#             self.camera_thread = None
#             self.face_reco.facePhotos.clear()

#     def update_image(self, frame):
#         self.photo = frame

#         # 每隔 10 帧检测一次
#         if self.frame_count % 10 == 0:
#             self.more_face.detect(self.photo)
#             self.face_reco.similar.setText(str(self.more_face.similarity))
#             self.face_reco.finalName.setText(self.more_face.name)

#         self.frame_count += 1
#         self.frame_count %= 10  # 防止数值过大

#         show = cv2.cvtColor(self.photo, cv2.COLOR_BGR2RGB)
#         height, width = self.photo.shape[:2]
#         showPhoto = QtGui.QImage(show.data, width, height, QtGui.QImage.Format.Format_RGB888)
#         ratio = max(width / self.face_reco.facePhotos.width(), height / self.face_reco.facePhotos.height())
#         showPhoto.setDevicePixelRatio(ratio)

#         self.face_reco.facePhotos.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
#         self.face_reco.facePhotos.setPixmap(QtGui.QPixmap.fromImage(showPhoto))
#         self.face_reco.facePhotos.setScaledContents(True)

#     '''屏幕居中'''
#     def center(self):
#         qr = self.frameGeometry()
#         cp = self.screen().availableGeometry().center()
#         qr.moveCenter(cp)
#         self.move(qr.topLeft())


# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     app.setWindowIcon(QIcon('logo.ico'))
#     myWidget = QmyRec()
#     myWidget.show()
#     sys.exit(app.exec())


